package vn.lumi.smarthome.ui;

import net.margaritov.preference.colorpicker.ColorPickerDialog;
import net.margaritov.preference.colorpicker.ColorPickerDialog.OnColorChangedListener;
import net.margaritov.preference.colorpicker.ColorPickerPanelView;
import vn.lumi.smarthome.Config;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.TBL_DeviceScene;
import vn.lumi.smarthome.io.database.TBL_DeviceState;
import vn.lumi.smarthome.io.database.TBL_Scene;
import vn.lumi.smarthome.io.model.Device;
import vn.lumi.smarthome.load.LoadDeviceList;
import vn.lumi.smarthome.ulti.LogUltis;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.actionbarsherlock.app.SherlockFragmentActivity;

public class AddSceneActivity extends SherlockFragmentActivity implements LoaderCallbacks<Device[]>,OnClickListener{
	private static final String TAG="AddSceneActivity";
	
	private ListView mListDevices;
	private Button mbtnTest;
	private Button mbtnOk;
	private Button mbtnCancel;
	private EditText medtName;
	 
	public static final String EXTRA_FLOOR_ID="floor_id";
	public static final String EXTRA_ROOM_ID="room_id";
	
	private int mFloorID;
	private int mRoomID;
	private DeviceListAdapter mDeviceListAdapter;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_addscene);
		init_view();
		
		Intent intent=getIntent();
		mFloorID=intent.getIntExtra(EXTRA_FLOOR_ID, -1);
		mRoomID=intent.getIntExtra(EXTRA_ROOM_ID, -1);
		LogUltis.i(TAG, "Data receive, floorid=["+mFloorID+"] room_id=["+mRoomID+"]");
		//load data
		getSupportLoaderManager().initLoader(0, null, this).forceLoad();
		setupActionbar();
	}
	
	private void init_view(){
		mListDevices=(ListView)findViewById(R.id.activity_addscene_list_device);
		mbtnCancel=(Button)findViewById(R.id.activity_addscene_btn_cancle);
		mbtnOk=(Button)findViewById(R.id.activity_addscene_btn_ok);
		mbtnTest=(Button)findViewById(R.id.activity_addscene_btn_test);
		medtName=(EditText)findViewById(R.id.activity_addscene_edt_name);
		
		mbtnCancel.setOnClickListener(this);
		mbtnOk.setOnClickListener(this);
		mbtnTest.setOnClickListener(this);
	}
	private void setupActionbar(){
		getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_actionbar));
		getSupportActionBar().setTitle(R.string.app_name);
	}

	@Override
	public Loader<Device[]> onCreateLoader(int arg0, Bundle arg1) {
		return new LoadDeviceList(getApplicationContext(), mFloorID, mRoomID);
	}

	@Override
	public void onLoadFinished(Loader<Device[]> arg0, Device[] devices) {
		for (int i = 0; i < devices.length; i++) {
			LogUltis.i(TAG, "DeviceName="+devices[i].getName());
			LogUltis.i(TAG, "DeviceType="+devices[i].getType_id());
			LogUltis.i(TAG, "DeviceState="+devices[i].getDeviceState().getValue());
		}
		mDeviceListAdapter=new DeviceListAdapter(this, devices);
		mListDevices.setAdapter(mDeviceListAdapter);
	}

	@Override
	public void onLoaderReset(Loader<Device[]> arg0) {
		
	}
	
	private static class DeviceListAdapter extends BaseAdapter{
		private static final String TAG="DeviceListAdapter";
		private ColorPickerDialog mDialog;
		private Context mContext;
		private Device[] mDevices;
		public DeviceListAdapter(Context context, Device[] devices) {
			mContext=context;
			mDevices=devices;
		}
		@Override
		public int getCount() {
			return mDevices.length;
		}

		@Override
		public Object getItem(int arg0) {
			return mDevices[arg0];
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}
//		
		@Override
		public int getViewTypeCount() {
			return Device.NUM_LAYOUT_TYPE;
		}
//		
		@Override
		public int getItemViewType(int position) {
//			LogUltis.i(TAG, "View Type="+(mDevices[position].getType_id()));
			return Device.getLayoutType(mDevices[position].getType_id());
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup arg2) {
			ViewHolder holder=null;
			LogUltis.e(TAG, "Position="+position);
			if(convertView==null){
				int layout_type=getItemViewType(position);
				switch (layout_type) {	
					
				case Device.TYPE_LAYOUT_ONOFF:
					convertView=View.inflate(mContext, R.layout.item_list_device_onoff_addscene, null);
					holder=new ViewHolder();
					holder.toggle=(ToggleButton)convertView.findViewById(R.id.item_list_device_onoff_toggle);
					holder.textView=(TextView)convertView.findViewById(R.id.item_list_device_onoff_txt_name);
					holder.checkBox=(CheckBox)convertView.findViewById(R.id.item_list_device_onoff_addscene_chb);
					LogUltis.i(TAG, "DEVICE_TYPE_ONOFF Name="+mDevices[position].getName()+" Position["+position+"]");
					
					holder.checkBox.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							mDevices[position].setSelected(((CheckBox)v).isChecked());
						}
					});
					holder.toggle.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							mDevices[position].setTurnOn(((ToggleButton)v).isChecked());
						}
					});
					
					convertView.setTag(holder);
					break;
				case Device.TYPE_LAYOUT_DIMMER:
					convertView=View.inflate(mContext, R.layout.item_list_device_dimmer_addscene, null);
					LogUltis.i(TAG, "DEVICE_TYPE_VALUECHANGE Name="+mDevices[position].getName()+" Position["+position+"]");
					holder=new ViewHolder();
					holder.toggle=(ToggleButton)convertView.findViewById(R.id.item_list_device_dimmer_addscene_toggle);
					holder.textView=(TextView)convertView.findViewById(R.id.item_list_device_dimmer_addscene_txt_name);
					holder.checkBox=(CheckBox)convertView.findViewById(R.id.item_list_device_dimmer_addscene_chb);
					holder.seekBar=(SeekBar)convertView.findViewById(R.id.item_list_device_dimmer_addscene_seekbar_change);
					
					holder.seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
						
						@Override
						public void onStopTrackingTouch(SeekBar seekBar) {
							mDevices[position].getDeviceState().setValue(seekBar.getProgress());
							LogUltis.i(TAG, "Device Name="+mDevices[position].getName());
							LogUltis.i(TAG, "Device Value="+mDevices[position].getDeviceState().getValue());
						}
						
						@Override
						public void onStartTrackingTouch(SeekBar seekBar) {
							
						}
						
						@Override
						public void onProgressChanged(SeekBar seekBar, int progress,
								boolean fromUser) {
							
						}
					});
					holder.checkBox.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							mDevices[position].setSelected(((CheckBox)v).isChecked());
						}
					});
					holder.toggle.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							mDevices[position].setTurnOn(((ToggleButton)v).isChecked());
						}
					});
					convertView.setTag(holder);					
					break;
				case Device.TYPE_LAYOUT_BLIND:
					convertView=View.inflate(mContext, R.layout.item_list_device_blind_addscene, null);
					holder=new ViewHolder();
					holder.textView=(TextView)convertView.findViewById(R.id.item_list_device_blind_addscene_txt_name);
					holder.toggle=(ToggleButton)convertView.findViewById(R.id.item_list_device_blind_addscene_toggle);
					holder.checkBox=(CheckBox)convertView.findViewById(R.id.item_list_device_blind_addscene_chb);
					
					holder.checkBox.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							mDevices[position].setSelected(((CheckBox)v).isChecked());
						}
					});
					holder.toggle.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							mDevices[position].setTurnOn(((ToggleButton)v).isChecked());
						}
					});
					convertView.setTag(holder);
					break;
				case Device.TYPE_LAYOUT_RGB:
					convertView=View.inflate(mContext, R.layout.item_list_device_rgb_addscene, null);
					holder=new ViewHolder();
					holder.textView=(TextView)convertView.findViewById(R.id.item_list_device_rgb_addscene_txt_name);
					holder.toggle=(ToggleButton)convertView.findViewById(R.id.item_list_device_rgb_addscene_toggle);
					holder.checkBox=(CheckBox)convertView.findViewById(R.id.item_list_device_rgb_addscene_chb);
					holder.colorPickerPanelView=(ColorPickerPanelView)convertView.findViewById(R.id.item_list_device_rgb_addscene_color_panel);
					
					final OnColorChangedListener onColorChangedListener=new OnColorChangedListener() {
						
						@Override
						public void onColorChanged(int color) {
							mDevices[position].getDeviceState().setRGB(color);
//							holder.colorPickerPanelView.setColor(color)
							notifyDataSetChanged();
						}
					};
					holder.colorPickerPanelView.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							showDialog(onColorChangedListener, Color.BLACK);
						}
					});
					holder.checkBox.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							mDevices[position].setSelected(((CheckBox)v).isChecked());
						}
					});
					holder.toggle.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							mDevices[position].setTurnOn(((ToggleButton)v).isChecked());
						}
					});
					convertView.setTag(holder);
					break;

				default:
					break;
				}
			}else{
				holder=(ViewHolder) convertView.getTag();
			}
			
			int layout_type=getItemViewType(position);
			switch (layout_type) {
			case Device.TYPE_LAYOUT_ONOFF:
//				holder.toggle.setChecked(mDevices[position].isTurnOn());
//				holder.checkBox.setChecked(mDevices[position].isSelected());
//				holder.textView.setText(mDevices[position].getName());
				setValueToView(mDevices[position], holder.toggle, holder.checkBox, holder.textView, position);
				setSelectorForDevice(mDevices[position].getType_id(), holder.toggle);
				break;
			case Device.TYPE_LAYOUT_DIMMER:
//				holder.toggle.setChecked(mDevices[position].isTurnOn());
//				holder.checkBox.setChecked(mDevices[position].isSelected());
//				holder.textView.setText(mDevices[position].getName());
				setValueToView(mDevices[position], holder.toggle, holder.checkBox, holder.textView, position);
				holder.seekBar.setProgress(mDevices[position].getDeviceState().getValue());
				setSelectorForDevice(mDevices[position].getType_id(), holder.toggle);
				break;
			case Device.TYPE_LAYOUT_BLIND:
//				holder.toggle.setChecked(mDevices[position].isTurnOn());
//				holder.checkBox.setChecked(mDevices[position].isSelected());
//				holder.textView.setText(mDevices[position].getName());
				setValueToView(mDevices[position], holder.toggle, holder.checkBox, holder.textView, position);
				setSelectorForDevice(mDevices[position].getType_id(), holder.toggle);
				break;
			case Device.TYPE_LAYOUT_RGB:
//				holder.toggle.setChecked(mDevices[position].isTurnOn());
//				holder.checkBox.setChecked(mDevices[position].isSelected());
//				holder.textView.setText(mDevices[position].getName());
				holder.colorPickerPanelView.setColor(mDevices[position].getDeviceState().getRGB());
				setValueToView(mDevices[position], holder.toggle, holder.checkBox, holder.textView, position);
				setSelectorForDevice(mDevices[position].getType_id(), holder.toggle);
				break;
			default:
				break;
			}
			return convertView;
		}
		
		private void setSelectorForDevice(int deviceType,ToggleButton toggleButton){
			switch (deviceType) {
			case Device.DEVICE_TYPE_DIMMER:
				toggleButton.setBackgroundResource(R.drawable.img_dimmer_selector);
				break;
			case Device.DEVICE_TYPE_FAN:
				toggleButton.setBackgroundResource(R.drawable.img_fan_selector);
				break;
			case Device.DEVICE_TYPE_AIRCON:
				toggleButton.setBackgroundResource(R.drawable.img_aircon_selector);
				break;
			case Device.DEVICE_TYPE_BLIND:
				toggleButton.setBackgroundResource(R.drawable.img_blind_selector);
				break;
			case Device.DEVICE_TYPE_HEATER:
				toggleButton.setBackgroundResource(R.drawable.img_heater_selector);
				break;
			case Device.DEVICE_TYPE_LIGHT:
				toggleButton.setBackgroundResource(R.drawable.img_light_selector);
				break;
			case Device.DEVICE_TYPE_RGB:
				toggleButton.setBackgroundResource(R.drawable.img_rgb_selector);
				break;
			default:
				break;
			}
		}
		private void setValueToView(Device device,ToggleButton toggleButton,CheckBox checkBox,TextView textView,int position){
			toggleButton.setChecked(mDevices[position].isTurnOn());
			checkBox.setChecked(mDevices[position].isSelected());
			textView.setText(mDevices[position].getName());
		}
		
		public Device[] getDevices(){
			return mDevices;
		}
		
		private static class ViewHolder{
			public TextView textView;
			public CheckBox checkBox;
			public SeekBar seekBar;
			public ToggleButton toggle;
			public ColorPickerPanelView colorPickerPanelView;
		}
		
		protected void showDialog(OnColorChangedListener onColorChangedListener,int value) {
			mDialog = new ColorPickerDialog(mContext,value);
			mDialog.setOnColorChangedListener(onColorChangedListener);
			mDialog.show();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.activity_addscene_btn_cancle:
			finish();
			break;
		case R.id.activity_addscene_btn_ok:
			saveScene(mDeviceListAdapter.getDevices(),medtName.getText().toString());
			finish();
			break;
		case R.id.activity_addscene_btn_test:
			Device[] devices=mDeviceListAdapter.getDevices();
			for (int i = 0; i < devices.length; i++) {
				LogUltis.i(TAG, "Name=["+devices[i].getName()+"] vs Value=["+devices[i].getDeviceState().getValue()+"]");
			}
			break;

		default:
			break;
		}
	}
	
	private void saveScene(Device[] devices,String scene_name){
		//(1) Insert new row Scene to DB
//		ContentValues values=new ContentValues();
//		values.put(TBL_Scene.NAME,scene_name);
//		values.put(TBL_Scene.ROOM_ID, mRoomID);
//		values.put(TBL_Scene.STATE, 0);
//		Uri uri=getContentResolver().insert(TBL_Scene.CONTENT_URI_SCENE, values);
//		int idScene=Integer.parseInt(uri.getLastPathSegment());
//		LogUltis.i(TAG, "Insert row Scene to DB");
		//(1)//
		for(int i=0;i<devices.length;i++){
		
		//nhung thiet bi khong duoc chon thi khong luu
		if(!devices[i].isSelected())break;
		int deviceType=devices[i].getType_id();
		int device_id=devices[i].getId();
		
		LogUltis.i(TAG, "Name="+devices[i].getName());
		LogUltis.i(TAG, "State="+devices[i].getDeviceState().getValue());
		LogUltis.i(TAG, "RGB="+devices[i].getDeviceState().getRGB());
				
		
//		switch (deviceType) {
//		case Device.DEVICE_TYPE_DIMMER:
//		case Device.DEVICE_TYPE_FAN:
//			
//			break;
//		case Device.DEVICE_TYPE_AIRCON:
//		case Device.DEVICE_TYPE_BLIND:
//		case Device.DEVICE_TYPE_HEATER:
//		case Device.DEVICE_TYPE_LIGHT:
//		case Device.DEVICE_TYPE_RGB:
//			break;
//		default:
//			break;
//		}
//		//(2) Insert DeviceState
//		ContentValues  contentValues=new ContentValues();
//		contentValues.put(TBL_DeviceState.VALUE, devices[i].getDeviceState().getValue());
//		contentValues.put(TBL_DeviceState.RGB, devices[i].getDeviceState().getRGB());
//		Uri uri2=getContentResolver().insert(TBL_DeviceState.CONTENT_URI_DEVICE_STATE, contentValues);
//		contentValues.clear();
//		int state_id=Integer.parseInt(uri2.getLastPathSegment());
//		LogUltis.i(TAG, "Insert DeviceState");
//		//(2)//
//		
//		//(3) Insert to DeviceScene
//		contentValues.put(TBL_DeviceScene.DEVICE_ID,device_id);
//		contentValues.put(TBL_DeviceScene.SCENE_ID,idScene);
//		contentValues.put(TBL_DeviceScene.STATE_ID,state_id);
//		LogUltis.i(TAG, "Insert DeviceScene");
//		getContentResolver().insert(TBL_DeviceScene.CONTENT_URI_DEVICE_SCENE, contentValues);
//		//(3)//
		}
		Toast.makeText(getApplicationContext(), R.string.txt_save_scene_success,Toast.LENGTH_LONG).show();
	}
	
}
